﻿using AutoMapper;
using SmarterCharger.Library.Model;
using SmarterCharger.Library.Repositories.Interfaces;
using SmarterCharger.Library.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace SmarterCharger.Library.Services
{
    internal class SmartPlugLoader : ISmartPlugLoader
    {
        private readonly List<string> _smartPlugHardwareModels = new List<string> { "niko", "plugwise" };
        private readonly IEnergyDeviceRepository _energyDeviceRepository;

        public SmartPlugLoader(IEnergyDeviceRepository energyDeviceRepository)
        {
            if (energyDeviceRepository == null) throw new ArgumentNullException("energyDeviceRepository");

            _energyDeviceRepository = energyDeviceRepository;
        }

        public async Task<LoadSmartPlugResult> Load(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username)) throw new ArgumentNullException("username");
            if (string.IsNullOrWhiteSpace(password)) throw new ArgumentNullException("password");

            var energyDevices = await _energyDeviceRepository.GetEnergyDevices(username, password);

            switch (energyDevices.StatusCode)
            {
                case HttpStatusCode.OK:
                    var smartPlugs = energyDevices.Result.Where(d => _smartPlugHardwareModels.Contains(d.HWModel));
                    var mappedSmartPlugs = Mapper.Map<IEnumerable<SmartPlug>>(smartPlugs);

                    return new LoadSmartPlugResult { IsCredentialsValid = true, SmartPlugs = mappedSmartPlugs };

                case HttpStatusCode.Unauthorized:
                    return new LoadSmartPlugResult { IsCredentialsValid = false };

                default:
                    throw new Exception(string.Format("Failed to load smartplugs, did not expect '{0}'. This could be a temporary error, please try again.", 
                        energyDevices.StatusCode.ToString()));
            }
        }

        internal static void ConfigureMapping(IConfiguration configuration)
        {
            configuration.CreateMap<EnergyDevice, SmartPlug>();
        }
    }
}
